package com.swjd.Interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
//HandlerInterceptor拦截器
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取访问路径
        String url = request.getRequestURI();
        //获取session中的用户名
        Object loginUser = request.getSession().getAttribute("loginUser");
        //如果访问的是admin界面，且用户名为空，就拦截并重定向到toLoginPage页面
        if(url.startsWith("/admin")&&loginUser==null){
            response.sendRedirect("/toLoginPage");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        //获取年份
        int i = Calendar.getInstance().get(Calendar.YEAR);
        //将年份绑定到前台页面
        request.setAttribute("currentYear",i);
    }
}
